package com.topsun.framework.common.core.util;

import cn.hutool.core.util.ObjectUtil;
import com.topsun.framework.common.core.enums.ContentTypeEnum;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.MultimediaInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * 
 * @author: 皮皮
 * @date: 2022/3/13 9:42 上午
 */
@Slf4j
public class AudioUtil {

    /**
     * 音频文件获取文件时长
     *
     * @param source
     * @return
     */
    public static Long getDuration(File source) {

        Encoder encoder = new Encoder();
        try {
            MultimediaInfo m = encoder.getInfo(source);
            return m.getDuration() / 1000;
        } catch (Exception e) {
            log.error("获取音频时长有误，file = {}", source.getAbsolutePath(), e);
        }
        return null;
    }

    /**
     * 获取Url的音频文件时长
     * @param url
     * @return
     */
    public static Long getDurationByUrl(String url) {
        String tmpFile = null;
        try {
            tmpFile = FileUtil.saveUrlTmpFile(url);
            return getDuration(new File(tmpFile));
        } catch (IOException e) {
            log.error("获取音频时长有误，url = {}", url, e);
        } finally {
            if (null != tmpFile) {
                FileUtil.del(tmpFile);
            }
        }
        return null;
    }

    /**
     * 音频转MP3
     * @param audioFile
     * @return
     */
    private static byte[] audio2Mp3(File audioFile) throws IOException {
        if (ObjectUtil.isNull(audioFile)) {
            return null;
        }
        String mp3Path = audioFile.getAbsolutePath();
        int index = mp3Path.lastIndexOf(".");
        if (index >= 0) {
            mp3Path = mp3Path.substring(0, index) + ".mp3";
        } else {
            mp3Path = mp3Path + StringPool.DOT + ContentTypeEnum.AUDIO_MPEG.getFileSuffix();
        }
        File mp3File = new File(mp3Path);
        try {
            AudioAttributes audio = new AudioAttributes();
            audio.setCodec("libmp3lame");
            EncodingAttributes attrs = new EncodingAttributes();
            attrs.setFormat("mp3");
            attrs.setAudioAttributes(audio);
            try {
                Encoder encoder = new Encoder();
                encoder.encode(audioFile, mp3File, attrs);
            } catch (Exception e) {
                throw new RuntimeException(String.format("音频转换mp3错误, audioPath is %s, exceptionMessage is %s", audioFile.getAbsolutePath(), e.getMessage()), e);
            }

            return  FileUtil.readBytes(mp3File);
        } finally {
           FileUtil.del(mp3File);
        }
    }

    /**
     * 音频文件转换成MP3文件
     *
     * @param
     */
    public static byte[] audio2Mp3(InputStream inputStream) throws IOException {
        return audio2Mp3(FileCopyUtils.copyToByteArray(inputStream));
    }

    /**
     * 音频文件转换成MP3文件
     *
     * @param
     */
    public static byte[] audio2Mp3(String url) throws IOException {
        return audio2Mp3(new URL(url).openStream());
    }

    /**
     * 音频转换MP3
     * @param audioBytes
     * @return
     * @throws IOException
     */
    @SuppressWarnings("all")
    public static byte[] audio2Mp3(byte[] audioBytes) throws IOException {
        if (ObjectUtil.isNull(audioBytes) || audioBytes.length == 0) {
            return null;
        }
        String tmpFileName = FileUtil.tmpFilePath();
        File audioFile = new File(tmpFileName);
        audioFile.createNewFile();
        try {
            FileUtil.writeFromStream(new ByteArrayInputStream(audioBytes), audioFile);
            return audio2Mp3(audioFile);
        } finally {
            FileUtil.del(audioFile);
        }
    }

    public static void main(String[] args) {
        System.out.println(getDuration(new File("/Users/pipi/Desktop/2b71e21d-e8bc-4b6e-bf77-af84c6c1f593.mp3")));
    }
}
